import { Injectable } from "@nestjs/common";
import axios from 'axios';


@Injectable()
export class WxService {
    appid = 'wxecebe41f54635828';
    secret = '44f69bbbcb6208c40edce94736f7ffaf';

    constructor() {
    }

    async code2Session(loginCode: string) {
        const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${this.appid}&secret=${this.secret}&js_code=${loginCode}&grant_type=authorization_code`;
        const resWx = await axios.get(url);
        // {"session_key":"ywalTRZL5crfeLTg==","openid":"oaTi55"}
        console.log("response from wx", resWx)
        const data = resWx?.data;
        const openid = data?.openid;
        const session_key = data?.session_key;
        return {
            openId: openid,
            sessionKey: session_key
        };
    }


    async getUserPhoneNumber(tmpCode: string) {
        // 获取 access_token
        const tokenUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.appid}&secret=${this.secret}`;
        try {
            const wxToken = await axios.get(tokenUrl);
            if (wxToken.data && wxToken.data.access_token) {
                const accessToken = wxToken.data.access_token;
                console.log("get wxToken before query phoneNumber: ", accessToken);
                console.log("get code before query phoneNumber: ", tmpCode);
                // 调用获取用户手机号码的接口
                const getPhoneUrl = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${accessToken}`;
                const phoneData = await axios.post(getPhoneUrl, { code: tmpCode });
                if (phoneData.data && phoneData.data.errmsg === 'ok') {
                    const phoneNumber = phoneData.data.phone_info.phoneNumber;
                    console.log("User phone number:", phoneNumber);
                    return phoneNumber;
                } else {
                    console.error("Failed to get user phone number:", phoneData.data);
                    return null;
                }
            } else {
                console.error("Failed to get wxToken:", wxToken.data);
                return null;
            }
        } catch (error) {
            console.error("Error occurred:", error);
            return null;
        }
    }

}